﻿using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Simple.Tfs{
    internal class Program{
        private static void Main(string[] args){
            if (args == null){
                displayHelp();
                return;
            }

            string collectionPath = args[0];
            string downloadFolder = args[1];
            Uri projectCollectionUri = new Uri(collectionPath);
            TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(projectCollectionUri);
            AttachmentController controller = new AttachmentController(teamProjectCollection){DownloadFolder = downloadFolder, DirectoryPerWorkItem = false};
            controller.DownloadStarted += (sender, e) =>{
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("[DOWNLOADING] ");
                Console.ResetColor();
                Console.Write(e.FileName);
            };
            controller.DownloadCompleted += (sender, e) =>{
                Console.SetCursorPosition(0, Console.CursorTop);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("[COMPLETED]  ");
                Console.ResetColor();
            };

            Console.WriteLine("ProjectCollectionUri: {0}", projectCollectionUri);
            Console.WriteLine("DownloadFolder: {0}", controller.DownloadFolder);
            Console.WriteLine("DirectoryPerWorkItem: {0}", controller.DirectoryPerWorkItem);
            Console.WriteLine("------------------------------");
            Console.WriteLine("Retrieving Work Items...");
            try{
                WorkItemCollection collection = controller.GetWorkItems("SELECT [System.Id] FROM workitems where [System.AttachedFileCount]>0");
                controller.Download(collection);
            }
            catch (Exception exception){
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                for (Exception eCurrent = exception; eCurrent != null; eCurrent = eCurrent.InnerException){
                    Console.WriteLine(eCurrent.Message);
                }
                Console.ResetColor();
                displayHelp();
            }

            Console.Read();
        }

        private static void displayHelp(){
            Console.WriteLine("Please specify Project Collection and Output Folder.");
            Console.WriteLine("  For example:");
            Console.WriteLine("  Downloader.exe http://[server]:8080/tfs/DefaultCollection c:\attachments");
        }
    }
}